package com.seven.leetcode.problems;

import java.util.Arrays;
import java.util.Comparator;

/**
 * 14. 最长公共前缀
 * LongestCommonPrefix
 * https://leetcode-cn.com/problems/longest-common-prefix/
 * 级别：Medium
 * <p>
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * <p>
 * 如果不存在公共前缀，返回空字符串""。
 * <p>
 * 示例 1：
 * <p>
 * 输入：strs = ["flower","flow","flight"]
 * 输出："fl"
 * 示例 2：
 * <p>
 * 输入：strs = ["dog","racecar","car"]
 * 输出：""
 * 解释：输入不存在公共前缀。
 *
 * @author : wenguang
 * @date : 2021/3/22 9:26
 */
public class LongestCommonPrefix {

    public static void main(String[] args) {
        String[] strings = new String[]{"flower", "flow", "flight"};
        System.out.println("in: \nstrings->" + Arrays.toString(strings));
        String result = longestCommonPrefix1(strings);
        System.out.println("out: " + result);
    }

    public static String longestCommonPrefix1(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        String prefix = strs[0];
        int count = strs.length;
        for (int i = 1; i < count; i++) {
            prefix = longestCommonPrefix(prefix, strs[i]);
            if (prefix.length() == 0) {
                break;
            }
        }
        return prefix;
    }

    public static String longestCommonPrefix(String str1, String str2) {
        int length = Math.min(str1.length(), str2.length());
        int index = 0;
        while (index < length && str1.charAt(index) == str2.charAt(index)) {
            index++;
        }
        return str1.substring(0, index);
    }

    public static String longestCommonPrefix2(String[] strs) {
        String res = "";
        int length = strs.length;
        if (length > 0) {
            Arrays.sort(strs, 0, strs.length - 1, Comparator.comparingInt(String::length));
            String first = strs[0];
            int l = first.length();
            String[] arr = new String[l];

            for (int i = l - 1; i >= 0; i--) {
                arr[l - i - 1] = first.substring(0, i + 1);
            }

            for (int i = 0; i < l; i++) {
                String prefix = arr[i];
                boolean shouldBreak = true;
                for (int j = 1; j < length; j++) {
                    boolean b = strs[j].startsWith(prefix);

                    if (!b) {
                        shouldBreak = false;
                        break;
                    }
                }

                if (shouldBreak) {
                    res = prefix;
                    break;
                }
            }
        }

        return res;
    }
}
